var _columns;
var _newcolumns;
var TableInit = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        $('#data_table').bootstrapTable({
            url: '/entity_sensor/select', //请求后台的URL（*）
            method: 'get', //请求方式（*）
            toolbar: '#toolbar', //工具按钮用哪个容器
            cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true, //是否显示分页（*）
            queryParams: oTableInit.queryParams, //传递参数（*）
            sidePagination: "client", //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1, //初始化加载第一页，默认第一页
            pageSize: 10, //每页的记录行数（*）
            pageList: [10, 25, 50, 100], //可供选择的每页的行数（*）
            showColumns: true, //是否显示所有的列
            showRefresh: true, //是否显示刷新按钮
            clickToSelect: true, //是否启用点击选中行
            uniqueId: "id", //每一行的唯一标识，一般为主键列
            sortable: true, //是否启用排序
            sortOrder: "desc",
            columns: _columns,
        });
    };
    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = { //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            limit: params.limit, //页面大小
            offset: params.offset, //页码
            sort: params.sort, //排序列名
            sortOrder: params.order, //排序列名(desc,asc)
            techProcessId: label_id
        };
        return temp;

    };
    return oTableInit;
};

function create_column(csName, enName, value, num) {
    if (typeof (value) == "undefined")
        value = ''
    var pre;
    if (num == 0) {
        pre = "new";
    } else {
        pre = "edit";
    }
//    if (enName == pre + "SORT") {
//        var result = '<div class="form-group"><label>' + csName + '</label><select  id="' + enName + '"value="' + value + '" class="form-control selectpicker" data-live-search="true"></select></div>'
//    } else if (enName == pre + "NAME" || enName == pre + "WORKSHOP" || enName == pre + "OBJECT_NAME" || enName == pre + "UNIT" || enName == pre + "OPERATOR") {
//        var result = '<div class="form-group"><label>' + csName + '</label><input class="form-control" placeholder="必填"  id="' + enName + '" value="' + value + '"></div>';
//    } else {
//        var result = '<div class="form-group"><label>' + csName + '</label><input class="form-control" placeholder="选填"  id="' + enName + '" value="' + value + '"></div>';
//    }
    if (csName == "设备类型") {
        var result = '<div class="form-group"><label>' + csName + '</label><select  id="' + enName + '"value="' + value + '" class="form-control selectpicker" data-live-search="true"></select></div>'
    } else if (csName == "设备编号" || csName == "设备名称" || csName == "型号规格") {
        var result = '<div class="form-group"><label>' + csName + '</label><input class="form-control" placeholder="必填"  id="' + enName + '" value="' + value + '"></div>';
    } else {
        var result = '<div class="form-group"><label>' + csName + '</label><input class="form-control" placeholder="选填"  id="' + enName + '" value="' + value + '"></div>';
    }
    return result;
}


var ButtonInit = function () {
    var oInit = new Object();
    oInit.Init = function () {
        //初始化页面上面的按钮事件

        //新增按钮
        $("#btn_add").click(function () {
            // 跳过 checkbox 和 id,showId
            $('#new_data_body').empty();
            var typeEn;
            var numEn;
            //当 DOM ID有一个空格时,使用属性选择器$("[id='content Module']").whatever();
            for (var i = 3; i < _columns.length; i++){
                $('#new_data_body').append(create_column(_columns[i].title, 'new' + _columns[i].field, '', 0));
                if(_columns[i].title=="设备类型")
                    typeEn="[id='new" + _columns[i].field+"']"
                if(_columns[i].title=="设备编号")
                    numEn="[id='new"+ _columns[i].field+"']"
            }

            $(typeEn).append('<option value="压力传感器">压力传感器</option>');
            $(typeEn).append('<option value="温度传感器">温度传感器</option>');
            $(typeEn).append('<option value="流量传感器">流量传感器</option>');
            $(typeEn).append('<option value="水质传感器">水质传感器</option>');

            let substr = "YL_"
            $(numEn).val(substr)
            $(typeEn).change(function () {
                let sortName = $(numEn).val()
                let type = $(typeEn).val()
                let temp1 = sortName.indexOf("YL_")
                let temp2 = sortName.indexOf("WD_")
                let temp3 = sortName.indexOf("LL_")
                let temp4 = sortName.indexOf("SZ_")
                if (type == "压力传感器") {
                    if (temp1 == -1) {
                        if (temp2 != -1 || temp3 != -1 || temp4 != -1) {
                            let substr = sortName.substring(3, sortName.length)
                            substr = "YL_" + substr
                            $(numEn).val(substr)
                        } else {
                            let substr = "YL_" + sortName
                            $(numEn).val(substr)
                        }
                    }
                }
                if (type == "温度传感器") {
                    if (temp2 == -1) {
                        if (temp1 != -1 || temp3 != -1 || temp4 != -1) {

                            let substr = sortName.substring(3, sortName.length)
                            substr = "WD_" + substr
                            $(numEn).val(substr)
                        } else {
                            let substr = "WD_" + sortName
                            $(numEn).val(substr)
                        }
                    }
                }
                if (type == "流量传感器") {
                    if (temp3 == -1) {
                        if (temp1 != -1 || temp2 != -1 || temp4 != -1) {
                            let substr = sortName.substring(3, sortName.length)
                            substr = "LL_" + substr
                            $(numEn).val(substr)
                        } else {
                            let substr = "LL_" + sortName
                            $(numEn).val(substr)
                        }
                    }
                }
                if (type == "水质传感器") {
                    if (temp4 == -1) {
                        if (temp1 != -1 || temp2 != -1 || temp3 != -1) {
                            let substr = sortName.substring(3, sortName.length)
                            substr = "SZ_" + substr
                            $(numEn).val(substr)
                        } else {
                            let substr = "SZ_" + sortName
                            $(numEn).val(substr)
                        }
                    }
                }
            })
            $('#new_data').modal();

        });

        //编辑按钮
        $("#btn_edit").click(function () {
            var arrselections = $("#data_table").bootstrapTable('getSelections');

            if (arrselections.length > 1) {
                bootoast({
                    message: '只能选择一行进行编辑',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }
            if (arrselections.length <= 0) {
                bootoast({
                    message: '请选择有效数据',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }
            values = [];
            values.push(arrselections[0].ID);
            $.ajax({
                type: "post",
                url: "/entity_sensor/queryEntityStatus",
                data: JSON.stringify(values),
                contentType: "application/json",
                success: function (data) {
                    if (data['status'] == "failed") {
                        bootoast({
                            message: data['msg'],
                            position: 'top',
                            type: 'danger',
                            timeout: 1.5,
                        });
                    } else {
                        $('#edit_data_body').empty();
                        var typeEn;
                        var numEn;
                        for (var i = 3; i < _columns.length; i++){
                            $('#edit_data_body').append(create_column(_columns[i].title, 'edit' + _columns[i].field, arrselections[0][_columns[i].field], 1));
                            if(_columns[i].title=="设备类型")
                                typeEn="[id='edit" + _columns[i].field+"']"
                            if(_columns[i].title=="设备编号")
                                numEn="[id='edit"+ _columns[i].field+"']"
                        }

                        $(typeEn).append('<option value="压力传感器">压力传感器</option>');
                        $(typeEn).append('<option value="温度传感器">温度传感器</option>');
                        $(typeEn).append('<option value="流量传感器">流量传感器</option>');
                        $(typeEn).append('<option value="水质传感器">水质传感器</option>');
                        $(typeEn).val(arrselections[0][_columns[4].field])
                        $(typeEn).change(function () {

                            let sortName = $(numEn).val()
                            let type = $(typeEn).val()
                            let temp1 = sortName.indexOf("YL_")
                            let temp2 = sortName.indexOf("WD_")
                            let temp3 = sortName.indexOf("LL_")
                            let temp4 = sortName.indexOf("SZ_")
                            if (type == "压力传感器") {
                                if (temp1 == -1) {
                                    if (temp2 != -1 || temp3 != -1 || temp4 != -1) {

                                        let substr = sortName.substring(3, sortName.length)
                                        substr = "YL_" + substr
                                        $(numEn).val(substr)
                                    } else {
                                        let substr = "YL_" + sortName
                                        $(numEn).val(substr)
                                    }
                                }
                            }
                            if (type == "温度传感器") {
                                if (temp2 == -1) {
                                    if (temp1 != -1 || temp3 != -1 || temp4 != -1) {

                                        let substr = sortName.substring(3, sortName.length)
                                        substr = "WD_" + substr
                                        $(numEn).val(substr)
                                    } else {
                                        let substr = "WD_" + sortName
                                        $(numEn).val(substr)
                                    }
                                }
                            }
                            if (type == "流量传感器") {
                                if (temp3 == -1) {
                                    if (temp1 != -1 || temp2 != -1 || temp4 != -1) {
                                        let substr = sortName.substring(3, sortName.length)
                                        substr = "LL_" + substr
                                        $(numEn).val(substr)
                                    } else {
                                        let substr = "LL_" + sortName
                                        $(numEn).val(substr)
                                    }
                                }
                            }
                            if (type == "水质传感器") {
                                if (temp4 == -1) {
                                    if (temp1 != -1 || temp2 != -1 || temp3 != -1) {
                                        let substr = sortName.substring(3, sortName.length)
                                        substr = "SZ_" + substr
                                        $(numEn).val(substr)
                                    } else {
                                        let substr = "SZ_" + sortName
                                        $(numEn).val(substr)
                                    }
                                }
                            }
                        })
                        $('#edit_data').modal()
                    }
                }
            });
        });

        $("#btn_return").click(function () {
            $('#page-wrapper').load('pages/technological_process.html');
        })

        // 删除按钮
        $("#btn_delete").click(function () {
            var arrselections = $("#data_table").bootstrapTable('getSelections');
            if (arrselections.length <= 0) {
                bootoast({
                    message: '请选择有效数据',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }

            values = [];
            for (var i = 0; i < arrselections.length; i++)
                values.push(arrselections[i].ID);

            bootbox.confirm({
                message: "确认要删除选择的数据吗？",
                locale: 'zh_CN',
                title: '操作提示',
                callback: function (result) {
                    if (result) {
                        $.ajax({
                            type: "post",
                            url: "/entity_sensor/delete",
                            data: JSON.stringify(values),
                            contentType: "application/json",
                            success: function (data) {
                                if (data['status'] == "success") {
                                    bootoast({
                                        message: '删除成功',
                                        position: 'top',
                                        type: 'success',
                                        timeout: 1.5,
                                    });
                                    $("#data_table").bootstrapTable('refresh');
                                } else {
                                    bootoast({
                                        message: '删除失败\n' + data['msg'],
                                        position: 'top',
                                        type: 'danger',
                                        timeout: 1.5,
                                    });
                                }
                            }
                        });
                    }
                }
            })

        });

        //新增框内的提交
        $('#new_data_submit').click(function () {
            var values = []
            values.push("techProcessId")
            values.push(label_id)//这里相当于先添加techProcessId
            for (var i = 3; i < _columns.length; i++) {
                var name = "[id='new"+_columns[i].field+"']"
                if (fieldIsEmpty($(name).val(), _columns[i].title + '不能为空', '')) {
                    return false;
                } //判断校验
                values.push(_columns[i].field)
                values.push($(name).val())
            }
            $.ajax({
                type: "post",
                url: "/entity_sensor/insert",
                data: JSON.stringify(values),
                contentType: "application/json",
                success: function (data) {
                    if (data['status'] == "success") {
                        bootoast({
                            message: '插入成功',
                            position: 'top',
                            type: 'success',
                            timeout: 2,
                        });
                        $("#new_data").modal('hide');
                        $("#data_table").bootstrapTable('refresh');
                    } else {
                        bootoast({
                            message: '插入失败\n' + data['msg'],
                            position: 'top',
                            type: 'danger',
                            timeout: 2,
                        });
                    }
                },
                error: function () {
                    bootoast({
                        message: '通讯异常',
                        position: 'top',
                        type: 'danger',
                        timeout: 1.5,
                    });
                }
            });
        });

        //编辑框内的提交
        $('#edit_data_submit').click(function () {
            var values = []
            values.push("ID")
            var id = $("#data_table").bootstrapTable('getSelections')[0]['ID'];
            values.push(id)
            for (var i = 3; i < _columns.length; i++) {
                var name = "[id='edit"+_columns[i].field+"']"
                if (fieldIsEmpty($(name).val(), _columns[i].title + '不能为空', '')) {
                    return false;
                } //判断校验
                values.push(_columns[i].field)
                values.push($(name).val())
            }

            $.ajax({
                type: "post",
                url: "/entity_sensor/update",
                data: JSON.stringify(values),
                contentType: "application/json",
                success: function (data) {
                    if (data['status'] == "success") {
                        bootoast({
                            message: '修改成功',
                            position: 'top',
                            type: 'success',
                            timeout: 2,
                        });
                        $("#edit_data").modal('hide');
                        $("#data_table").bootstrapTable('refresh');
                    } else {
                        bootoast({
                            message: '修改失败\n' + data['msg'],
                            position: 'top',
                            type: 'danger',
                            timeout: 2,
                        });
                    }
                },
                error: function () {
                    bootoast({
                        message: '通讯异常',
                        position: 'top',
                        type: 'danger',
                        timeout: 1.5,
                    });
                }
            });

        });

    };

    return oInit;
};

function hasPermission() {
    queryPermission('设备管理/实体数据管理', '新增', 'btn_add')
    queryPermission('设备管理/实体数据管理', '编辑', 'btn_edit')
    queryPermission('设备管理/实体数据管理', '删除', 'btn_delete') 
}

/**
 * 首先获取表格的表头数据
 */
function getColumns() {
    $.ajax({
        url: "/entity_sensor/selectColumn",
        type: 'post',
        data: {
            'id': 1,
            'enName': 'enName',
            'csName': 'csName',
            'definition': 'definition',
            'dataType': 'dataType',
            'techProcessId': label_id,
        },
        dataType: 'json',
        async: false,
        cache: false,
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        success: function (data) {
            _columns = data;
            _columns.unshift({
                checkbox: true
            });
            //排序
            for (var i = 1; i < _columns.length; i++) {
                _columns[i].sortable = "true";
            };
            //插入显示序号
            var showIdMap = {
                field: "showId",
                title: "序号",
                sortable: true,
                formatter: function (value, row, index) {
                    return index + 1;
                }
            };
            _columns.splice(2, 0, showIdMap);
        }
    });
}


$(function () {
    getColumns()
//     $.ajax({
//         url: "/entity_sensor/selectRealColumn",
//         type: 'post',
//         data: {
//             'id': 1,
//             'enName': 'enName',
//             'csName': 'csName',
//             'definition': 'definition',
//             'dataType': 'dataType',
//             'company_id': lid
// //            'company_id': label_id
//         },
//         dataType: 'json',
//         async: false,
//         cache: false,
//         contentType: "application/x-www-form-urlencoded; charset=utf-8",
//         success: function (data) {
//             _newcolumns = data;
//             _newcolumns.unshift({
//                 checkbox: true
//             });
//             //排序
//             for (var i = 1; i < _newcolumns.length; i++) {
//                 _newcolumns[i].sortable = "true";
//             };
//             //插入显示序号
//             var showIdMap = {
//                 field: "showId",
//                 title: "序号",
//                 sortable: true,
//                 formatter: function (value, row, index) {
//                     return index + 1;
//                 }
//             };
//             _newcolumns.splice(2, 0, showIdMap);
//         }
//     });
    //1.初始化Table
    var oTable = new TableInit();
    oTable.Init();

    //2.初始化Button的点击事件
    var oButtonInit = new ButtonInit();
    oButtonInit.Init();
    //3.隐藏列
    $('#data_table').bootstrapTable('hideColumn', 'ID');

    hasPermission()
});